package com.xinlin.framework.security.filter;

import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson2.JSON;
import com.xinlin.common.core.domain.AjaxResult;
import com.xinlin.common.core.domain.model.LoginAppUser;
import com.xinlin.common.utils.ServletUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import com.xinlin.common.core.domain.model.LoginUser;
import com.xinlin.common.utils.SecurityUtils;
import com.xinlin.common.utils.StringUtils;
import com.xinlin.framework.web.service.TokenService;
import org.springframework.web.util.ContentCachingResponseWrapper;

/**
 * token过滤器 验证token有效性
 *
 * @author xinlin
 */
@Component
@Slf4j
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
    @Autowired
    private TokenService tokenService;

    @Value("${app-plus.api-url}")
    private String apiUrl;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws ServletException, IOException {
        String url = request.getRequestURI();


//        ContentCachingResponseWrapper responseWrapper = new ContentCachingResponseWrapper(response);
//        chain.doFilter(request, responseWrapper);
//        if (responseWrapper.getStatus() == HttpStatus.NOT_FOUND.value()) {
//            // 处理404情况
//            log.info("404请求: " + ((HttpServletRequest)request).getRequestURI());
//            int code = 404;
//            String msg = StringUtils.format("请求访问：{}， 资源不存在", new Object[]{request.getRequestURI()});
//            ServletUtils.renderString(response, JSON.toJSONString(AjaxResult.error(code, msg)));
//            responseWrapper.copyBodyToResponse();
//            return;
//        }

        if (url.startsWith(apiUrl)) {
            LoginAppUser loginUser = tokenService.getLoginAppUser(request);
            if (StringUtils.isNotNull(loginUser) && StringUtils.isNull(SecurityUtils.getAuthentication())) {
                tokenService.verifyAppUserToken(loginUser);
                UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
                authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                SecurityContextHolder.getContext().setAuthentication(authenticationToken);
                log.info("App 用户 {} ....", loginUser.getUserId());
            } else {
                log.info("App 没有用户....apiUrl: {} ,url: {} ",apiUrl,url);
            }
        } else {

            LoginUser loginUser = tokenService.getLoginUser(request);
            if (StringUtils.isNotNull(loginUser) && StringUtils.isNull(SecurityUtils.getAuthentication())) {
                tokenService.verifyToken(loginUser);
                UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
                authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                SecurityContextHolder.getContext().setAuthentication(authenticationToken);
                log.info(".系统过滤器 用户 {} ....", loginUser.getUsername());
            } else {
                log.info(".系统过滤器 没有用户....apiUrl: {} ,url: {} ",apiUrl,url);
            }
        }

        chain.doFilter(request, response);


    }
}
